#!/usr/bin/env bash
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
PROCESSNAME='httptask.service'
ARGV=$1
CURRENTPATH=$(cd `dirname $0`; pwd)
PID=`ps x | grep $PROCESSNAME | grep -v grep | awk 'NR==1{print $1}'`

start(){
    if  [ ! -n "$PID" ] ;then
        $CURRENTPATH/httptask.service
        echo "Running Successfully!"
    else
        echo "The program is already running!  PID: $PID"
    fi
    sleep 1
    ps x | grep $PROCESSNAME | grep -v grep
}

stop(){
    if  [ ! -n "$PID" ] ;then
        echo "No such process";
    else
        # 向主进程发送SIGTERM也可以实现关闭服务器
        kill -15 $PID
        echo "Program stopped!"
    fi
}
reload(){
  if  [ ! -n "$PID" ] ;then
        start
    else
         # 重启所有worker进程
        kill -USR1 $PID
        echo "Program reloaded!"
    fi
}
restart(){
    stop
    $CURRENTPATH/httptask.service
    echo "Running Successfully!"
    sleep 1
    ps x | grep $PROCESSNAME | grep -v grep
}
status(){
    ps auxf | grep $PROCESSNAME | grep -v grep
}

install(){
    ln -s $CURRENTPATH/httptask /usr/bin/httptask
}

unstall(){
    rm /usr/bin/httptask
}

viewHelp(){
    echo -e "\033[32m
    Hey!
    You can try these commands \033[0m"
    echo "
    [1]  httptask start
    [2]  httptask stop
    [3]  httptask reload
    [4]  httptask restart
    [5]  httptask status
    "
}

if [[ $ARGV == "stop" ]]; then
stop
elif [[ $ARGV == "reload" ]]; then
reload
elif [[ $ARGV == "start" ]]; then
start
elif [[ $ARGV == "restart" ]]; then
restart
elif [[ $ARGV == "status" ]]; then
status
else
viewHelp
fi